package com.xiaoqiudong.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoqiudong.pojo.User;
import com.xiaoqiudong.pojo.game.Matcher;
import com.xiaoqiudong.pojo.game.OnlineUserManager;
import com.xiaoqiudong.pojo.request.MatchRequest;
import com.xiaoqiudong.pojo.response.MatchResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-16
 * Time:10:12
 */
@Component
public class MatchAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private Matcher matcher;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //玩家上线，加入OnManager中

        try{
            //1.获取用户信息
            User user = (User) session.getAttributes().get("user");
            //检查用户是否登录

            if (onlineUserManager.getGameHall(user.getUserId()) != null
                    ||onlineUserManager.getFromGameRoom(user.getUserId()) != null){
                MatchResponse matchResponse = new MatchResponse();
                matchResponse.setOk(true);
                matchResponse.setReason("用户已经登录，禁止多开");
                matchResponse.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));

//                session.close();
                return;
            }
            //3.设置在线状态
            onlineUserManager.enterGameHall(user.getUserId(),session);
            System.out.println("玩家"+user.getUsername()+"进入游戏大厅");

        }catch (NullPointerException e){
            System.out.println("[MatchAPI.afterConnectionEstablished] 当前用户未登录!");
            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("用户未登录,不能进行匹配");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理开始匹配和停止匹配
        User user = (User) session.getAttributes().get("user");
        String payload = message.getPayload();

        MatchRequest matchRequest = objectMapper.readValue(payload,MatchRequest.class);
        MatchResponse matchResponse = new MatchResponse();
        if("startMatch".equals(matchRequest.getMessage())){
            //进入匹配队列
            matcher.add(user);
            matchResponse.setOk(true);
            matchResponse.setMessage("startMatch");

        } else if ("stopMatch".equals(matchRequest.getMessage())) {
            //退出匹配队列
            matcher.remove(user);
            matchResponse.setOk(true);
            matchResponse.setMessage("stopMatch");

        }else {
            matchResponse.setOk(false);
            matchResponse.setReason("非法请求");
        }
        String jsonString = objectMapper.writeValueAsString(matchResponse);
        session.sendMessage(new TextMessage(jsonString));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        try{
            //玩家下线，从OnUserManager中删除
            User user = (User) session.getAttributes().get("user");

            WebSocketSession tmpSession = onlineUserManager.getGameHall(user.getUserId());
            if (session == tmpSession){
                onlineUserManager.exitGameHall(user.getUserId());
            }
            //如果玩家在匹配中，而websocket断开，退出匹配
            matcher.remove(user);
        }catch (NullPointerException e){
            System.out.println("用户未登录");
//            MatchResponse matchResponse = new MatchResponse();
//            matchResponse.setOk(false);
//            matchResponse.setReason("用户未登录,不能进行匹配");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //玩家下线，从OnUserManager中删除
        try{
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getGameHall(user.getUserId());
            if (session == tmpSession){
                onlineUserManager.exitGameHall(user.getUserId());
            }
            //如果玩家在匹配中，而服务器断开，退出匹配
            matcher.remove(user);
        }catch (NullPointerException e){
            System.out.println("用户未登录,不能进行匹配");
//            MatchResponse matchResponse = new MatchResponse();
//            matchResponse.setOk(false);
//            matchResponse.setReason("用户未登录,不能进行匹配");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }

    }
}
